import React, { useEffect, useState } from 'react'
import { Input, message, Card, Spin, Row, Col, Descriptions } from 'antd'
import { useNavigate, useParams } from 'react-router-dom'
import { $fetchStockInfo } from '../../api/stockApi'
import './StockInfo.scss'

const { Search } = Input

const StockInfo = () => {
  const navigate = useNavigate()
  const { symbol: paramSymbol } = useParams()
  const [data, setData]       = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError]     = useState('')

  useEffect(() => {
    if (!paramSymbol) {
      return;
  }

    // 如果 paramSymbol 无效，重定向到 /stock
    if (paramSymbol.length !== 8 || !/^(sh|sz)?\d{6}$/.test(paramSymbol)) {
        navigate('/stock', { replace: true });
        return;
    }

    
    setLoading(true)
    setError('')
    $fetchStockInfo(paramSymbol)
      .then(records => setData(records))
      .catch(err => {
        console.error(err)
        setError(err.message || '未知错误')
      })
      .finally(() => setLoading(false))
  }, [paramSymbol])

  const onSearch = value => {
    const code = value.trim()
    
    if (!code) {
      message.warning('请输入有效的股票代码，例如：sh600000 或 600000')
      return
    }
    navigate(`/stock/${code}`)
  }

  const renderContent = () => {
    if (!paramSymbol) {
      return <p className="stock-intro">请输入股票代码以查询个股信息。</p>
    }
    if (loading) {
      return <Spin tip="加载中..." className="spin-center" />
    }
    if (error) {
      if(error.includes('500'))
        {
          return (
            <Card type="inner" title="" style={{ marginTop: 20 }}>
              <p className="text-error">输入错误，请输入正确的股票代码。</p>
            </Card>
          )
        }
      else
      {
        return (
        <Card type="inner" title="错误" style={{ marginTop: 20 }}>
          <p className="text-error">{error}</p>
        </Card>
        )
      }
    }
    if (data.length === 0) {
      return <p className="stock-intro">未找到 “{paramSymbol}” 的任何信息。</p>
    }
    if (!paramSymbol || !/^(sh|sz)?\d{6}$/.test(paramSymbol)) {
      return; // 直接不拉了
    }
    
    return (
      <Card style={{ marginTop: 20 }} title={<span><strong>{paramSymbol}</strong> 个股信息</span>}>
        <div className="stock-info-container">
          <Descriptions
            bordered
            column={2}
            labelStyle={{ width: 150, fontWeight: 600 }}
            contentStyle={{ minWidth: 200 }}
          >
            {data.map(({ item, value }) => (
              <Descriptions.Item key={item} label={item}>
                {item.includes('时间')
                  ? String(value).replace(/^(\d{4})(\d{2})(\d{2})$/, '$1-$2-$3')
                  : value}
              </Descriptions.Item>
            ))}
          </Descriptions>
        </div>
      </Card>
    )
  }

  return (
    <div className="stock-page">
      <Row justify="center">
        <Col xs={24} sm={20} md={16} lg={12}>
          <h2 className="stock-title">📋 个股静态信息查询</h2>
          <Search
           placeholder="输入股票代码：sh600000 / sz000001 / 600000"
           enterButton="查询"
           allowClear
           defaultValue="" // 搜索框默认值为空
           onSearch={onSearch}
          />
          {renderContent()}
        </Col>
      </Row>
    </div>
  )
}

export default StockInfo
